var prefix = "/jzweb/jazSysProject";
$(function () {
    load();
});

var pages = 1,table=null;
const openS = (item, e) => {
    let mytr = $(e).parent().parent().parent()
    let d = JSON.parse(item.replaceAll("|", "\""))
    if ($(e).hasClass("layui-icon-triangle-r")) {
        //当前的tr,加入table
        const mytableId='exampleTable'+d.id
        const myWidth=mytr[0].clientWidth-508
        console.log('宽度获取', myWidth )
        $(mytr).after(`
		<tr class="myTr">
		  <td  colspan="7"  class="myTr_Td"> 
	        <table class="layui-hide" id="${mytableId}" lay-filter="${mytableId}"></table>
	      </td>
		</tr>
		`)
        // 创建渲染实例
        table.render({
            elem: `#${mytableId}`
            , id: `${mytableId}`
            , method: "get"
            , contentType: 'multipart/form-data'
            , url: "/jzweb/jazSysProjectType/listType"
            , cellMinWidth: 80
            ,page: false
            , where: {
                sysProjectId: d.id,
            }
            , defaultToolbar: false
            , loading: true
            , cols: [[
                {
                    field: 'sysProjectName',
                    title: '类型名称',
                    align: 'center',
                    width:200,
                },
                {
                    field: 'workType',
                    title: '工作类型',
                    align: 'center',
                    width: myWidth
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    align: 'center',
                    width: 150
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'center',
                    width:140,
                    templet: (d)=> {
                        var bj = '<a  class="btn btn-primary btn-sm ' + s_editContent_h+' " href="#" mce_href="#" title="编辑" onclick="addInfo(\''
                            + d.id + '\',\'' + 1+ '\',\'' + d.sysProjectName + '\',\'' + d.workType + '\',\'' + ('exampleTable'+d.sysProjectId) + '\')"><i class="fa fa-edit"></i></a> ';
                        //
                        var ss = '<a class="btn btn-success btn-sm '+s_removeContent_h+'" href="#" title="删除"  mce_href="#" onclick="addInfo(\''
                            + d.id + '\',\'' + 2+ '\',\'' + d.sysProjectName + '\',\'' + d.workType + '\',\'' + ('exampleTable'+d.sysProjectId) + '\')"><i class="fa fa-remove"></i></a>';

                        return  bj + ss;
                    }
                }
            ]]
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , parseData:  (res)=> { //将原始数据解析成 table 组件所规定的数据
                if (res.code != 0) {
                    return false;
                }
                console.log('mytableId',mytableId)
                const mydata=[]
                res.data.forEach(item=>{item.mytableId=mytableId;mydata.push(item)})
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "data": mydata
                };
            }
            , error: function (res, msg) {

            }

            , done: function (res) {
                form.render()
            }
        });
        $(e).removeClass('layui-icon-triangle-r')
        $(e).addClass('layui-icon-triangle-d')
    } else {
        $(e).removeClass('layui-icon-triangle-d')
        $(e).addClass('layui-icon-triangle-r')
        $(mytr).next().remove()
    }
}
function load() {

    layui.use(['table', 'form'], function () {
        table = layui.table, form = layui.form;

        // 创建渲染实例
        table.render({
            elem: '#exampleTable'
            , id: 'exampleTable'
            // prefix
            , url: prefix + "/list" // 此处为静态模拟数据，实际使用时需换成真实接口
            , cellMinWidth: 80
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , curr: pages //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , limit: 10
            }
            , request: {
                pageName: 'current',
                limitName: 'size'
            }
            , defaultToolbar: false
            , loading: true
            , cols: [[
                {
                    field: "",
                    title:'',
                    align: 'center',
                    maxWidth: 30,
                    templet:function (d) {
                        let myd = JSON.stringify(d).replaceAll("\"", "|")
                        return `<i class="layui-icon myIcons layui-icon-triangle-r"  onclick='openS("${myd}",this)'></i>`
                    }
                },
                {
                    field: 'name',
                    title: '项目名称',
                    align: 'center',
                    templet: function (d) {
                        return  d.name
                    }
                },
                {
                    field: 'sort',
                    align: 'center',
                    width:100,
                    title: '顺序'
                },
                {
                    field: 'multipleChoice',
                    align: 'center',
                    width:100,
                    title: '是否多选',
                    templet: (d) => {
                       return d.multipleChoice==0?'否':(d.multipleChoice==1?'是':'-')
                    }
                },
                {
                    field: 'status',
                    title: '项目状态',
                    width: 40,
                    align: 'center',
                    templet: (d) => {
                        return upAndDownPrices?((d.status == '0' ? `   <input type="checkbox" checked ` : '<input type="checkbox" ') + ` name="open"  value="${d.id}"
      title="启用|禁用" myid="${d.id}" lay-skin="switch" lay-filter="switchTest" title="是否启用"> 
						`):(d.status=='0'?'<span class="label label-primary">启用</span>':'<span class="label label-warning">禁用</span>')
                    }
                },
                {
                    field: 'createTime',
                    align: 'center',
                    width:200,
                    title: '创建时间'
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'center',
                    width:200,
                    templet: function (d) {


                        var e = '<a  class="btn btn-primary btn-sm '+s_edit_h+'" href="#" mce_href="#" title="编辑" onclick="edit(\''
                            + d.id
                            + '\')"><i class="fa fa-edit"></i></a> ';

                        var ss = '<a class="btn btn-success btn-sm '+s_remove_h+'" href="#" title="删除"  mce_href="#" onclick="remove(\''
                            + d.id
                            + '\')"><i class="fa fa-remove"></i></a>';

                        var a = ' <a  class="btn btn-primary btn-sm ' +s_addContent_h+ ' " href="#" mce_href="#" title="新增内容" onclick="addInfo(\''
                            + d.id + '\',\'' + 0 + '\',\'' + d.name + '\',\'' + '' + '\',\'' + ('exampleTable'+d.id)+ '\')"><i class="layui-icon layui-icon-addition fa" style="font-size: inherit;"></i></a> ';
                        //'exampleTable'+d.id
                        return e + ss + a ;
                    }
                }
            ]]
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                if (res.code != 0) {
                    return false;
                }
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    pages = obj.curr
                }
            }
            , error: function (res, msg) {
                console.log(res, msg)
            }

            , done: function (res) {
                layer.close()
            }
        });
        form.on('switch(switchTest)', function (data) {
            let id = $(data.othis[0].parentNode).find('input').attr('myid')
            var loadIndex = layer.load(0);
            $.ajax({
                url: prefix + "/condition",
                type: "post",
                data: {
                    'id': id,
                    status: this.checked ? 0 : 1
                },
                success: function (r) {
                    if (r.code == 0) {
                        layer.msg(r.msg);
                        load();
                        layer.close(loadIndex)
                    } else {
                        layer.msg(r.msg);
						load();
                        layer.close(loadIndex)
                    }
                }
            });

        })
    });
}

function addInfo(id,myIndex,name,workType,tableName) {
    if(myIndex==2){
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function () {
            $.ajax({
                url: "/jzweb/jazSysProjectType/remove",
                type: "post",
                data: {
                    'id': id
                },
                success: function (r) {
                    if (r.code == 0) {
                        layer.msg(r.msg);
                        //执行重载
                        table.reload(tableName);
                    } else {
                        layer.msg(r.msg);
                    }
                }
            });
        })
        return false
    }
    let toIndex = layer.open({
        type: 1,
        title: myIndex==0?'新增':myIndex==1?'编辑':'删除',
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        area: ['400px', '300px'],
        content: `
<form class="layui-form layui-form-pane" style="width: 100%;height: 100%;padding: 10px;" id="myForm">
    	<div class="layui-form-item">
			<label class="layui-form-label required">类型名称</label>
			<div class="layui-input-block">
				<input type="text" name="name" lay-verify="required" autocomplete="off" placeholder="请输入" class="layui-input" value="${null!=name?name:''}" disabled>
			</div>
		</div>
			<div class="layui-form-item">
			<label class="layui-form-label required">工作类型</label>
			<div class="layui-input-block">
				<input type="text" name="workType" lay-verify="required" autocomplete="off" placeholder="请输入" class="layui-input" value="${null!=workType?workType:''}">
			</div>
		</div>
  <div class="layui-form-item" style="display: flex;    justify-content: center;">
    <button class="btn btn-success" type="button"  lay-submit lay-filter="layedit-code-yes">提交</button>
  </div>
</form>
                `,
        success: function (layero, index) {
            layui.use(['form', 'upload'], async function () {
                var form = layui.form;
                form.on('submit(layedit-code-yes)', function (data) {
                    const mydata = data.field
                    delete mydata.name
                    console.log('提交数据', mydata)
                    if(myIndex==0){
                        mydata.sysProjectId=id
                        AjaxPost('/jzweb/jazSysProjectType/save', mydata).then(function (response) {
                            layer.msg("操作成功");
                            layer.close(index);
                            //执行重载
                            table.reload(tableName);
                        }).catch(error => {
                            layer.msg(error.msg)
                        })
                    }else{
                        mydata.id=id
                        AjaxPost('/jzweb/jazSysProjectType/update', mydata).then(function (response) {
                            layer.msg("操作成功");
                            layer.close(index);
                            //执行重载
                            table.reload(tableName);
                        }).catch(error => {
                            layer.msg(error.msg)
                        })
                    }
                });
            })


        }
    });
    // layer.full(toIndex);
}

$("#add").click(function () {
    layer.open({
        type: 2,
        title: '增加',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '520px'],
        content: prefix + '/add' // iframe的url
    });
})

function edit(id) {
    layer.open({
        type: 2,
        title: '编辑',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '520px'],
        content: prefix + '/edit/' + id // iframe的url
    });
}
function openAdd(id) {
    layer.open({
        type: 2,
        title: '编辑',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['800px', '520px'],
        content: prefix + '/edit/' + id // iframe的url
    });
}

function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/remove",
            type: "post",
            data: {
                'id': id
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    load();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

function changeState(id, number) {
    $.ajax({
        url: prefix + "/condition",
        type: "post",
        data: {
            'id': id,
            status: number
        },
        success: function (r) {
            if (r.code == 0) {
                layer.msg(r.msg);
                load();
            } else {
                layer.msg(r.msg);
            }
        }
    });
}